﻿using Kernel.Command.Demo.HelloWorld;
using Kernel.Command.Demo.User;
using Kernel.IService.Service.Demo;
using Kernel.Model.Demo;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using System.Net;
using System.Security.Claims;

namespace WebAPI.Areas.Demo.Controllers
{
    [ApiVersion("1.0", Deprecated = true)]
    [ApiVersion("2.0")]
    public class UserController : DemoBaseController
    {
        private IMediator mediator;
        ILogger<UserController> logger;

        public IEmailService EmailService { get; set; }

        public UserController(IMediator mediator, ILogger<UserController> logger)
        {
            this.mediator = mediator;
            this.logger = logger;
        }

        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("info/{id}"), MapToApiVersion("1.0")]
        //[Authorize(Roles = "admin,role1")] //admin、role1两个角色任意满足一个
        //[Authorize(AuthenticationSchemes = "Bearer")]
        [Authorize(Policy = "Permission")] //权限验证策略   注：不同的Authorize之间是并且的关系
        public async Task<IActionResult> GetUser_V1_0(string id)
        {
            // http://localhost:39274/api/v1/demo/user/info/566C32F61CC1204EE0540018FE2DA12B

            //获取API版本号
            var apiVersion = HttpContext.GetRequestedApiVersion().ToString();

            logger.LogWarning("apiVersion:" + apiVersion);

            SysUserInParams model = new SysUserInParams { userID = id };
            var result = await mediator.Send(new GetUserCommand(model));
            //result.apiVersion = HttpContext.GetRequestedApiVersion().ToString();//获取API版本号
            return Ok(result);
        }

        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("info/{id}"), MapToApiVersion("2.0")]
        [ApiExplorerSettings(GroupName = nameof(ApiGroupNames.SysMgr))]
        public async Task<IActionResult> GetUser_V2_0(string id)
        {
            // http://localhost:39274/api/v2/user/info/566C32F61CC1204EE0540018FE2DA12B

            SysUserInParams model = new SysUserInParams { userID = id };
            var result = await mediator.Send(new GetUserCommand_V2_0(model));
            //result.apiVersion = HttpContext.GetRequestedApiVersion().ToString();//获取API版本号
            return Ok(result);
        }

        [HttpGet]
        [Route("list"), MapToApiVersion("1.0")]
        public async Task<IActionResult> GetUserList_V1_0([FromQuery] SysUserInParams model)
        {
            //测试 MediatorR 的 Publish 模式
            //await _mediator.Publish(new Pro.Application.Commands.HelloWorld.V1_0.HelloWorldCommand());

            // http://localhost:39274/api/v1/user/list?pageIndex=1&pageSize=10

            var result = await mediator.Send(new GetUserListCommand(model));
            //result.apiVersion = HttpContext.GetRequestedApiVersion().ToString();//获取API版本号
            return Ok(result);
        }

        [HttpGet]
        [Route("list"), MapToApiVersion("2.0")]
        [AllowAnonymous]
        [ApiGroup(ApiGroupNames.Identity, ApiGroupNames.SysMgr)]
        public async Task<IActionResult> GetUserList_V2_1()
        {
            //测试 MediatorR 的 Publish 模式
            await mediator.Publish(new HelloWorldCommand());

            //ReportServerContext context = new ReportServerContext();
            //var users = context.Users;

            //生成token示例
            var claims = new Claim[]{
                new Claim(ClaimTypes.Name,"wyt"),
                new Claim(ClaimTypes.Role,"admin"),
                new Claim(ClaimTypes.Role,"role1"),
                new Claim("Tenant","2c30ceb7534f44869bd0487e187bb34d")
            };
            string token = JwtUtil.EncodeToken(claims);


            //return Ok(users.AsQueryable());
            return Ok(token);
        }

        /// <summary>
        /// 模拟登录，cookie认证
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        [Route("cookieLogin"), MapToApiVersion("1.0")]
        public async Task<IActionResult> TestCookieLogin()
        {
            var claims = new Claim[]
            {
                new Claim(ClaimTypes.Name, "Jeffcky"),
            };

            //当ClaimsIdentity.AuthenticationType为null或为空时,User.Identity.IsAuthenticated返回false.为避免这种情况,请停止使用无参数的ClaimsIdentity构造函数并使用接受authenticationType参数的重载：
            var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

            await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity));

            return Ok();
        }

        [HttpGet]
        [Authorize(AuthenticationSchemes = "Cookies")]
        [Route("cookieVisit"), MapToApiVersion("1.0")]
        public async Task<IActionResult> TestCookieVisit()
        {
            return Ok("携带cookie访问页面成功！");
        }

        [HttpGet]
        [Route("WriteCookie/{flag}"), MapToApiVersion("1.0")]
        public async Task<IActionResult> WriteCookie_V1_0(string flag)
        {
            Response.Cookies.Append("cookie_" + flag, flag);

            var result = new
            {
                RequestCookies = Request.Cookies
            };

            return Ok(result);
        }

        /// <summary>
        /// 演示跨服务http调用传递cookie，存储被调服务cooike再次请求（适用于登录后爬虫抓数据的场景）
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("ReadCookie"), MapToApiVersion("1.0")]
        public async Task<IActionResult> ReadCookie_V1_0()
        {
            Uri baseUri = new Uri("http://localhost:39274/");
            var handler = new HttpClientHandler();            
            var client = new HttpClient(handler) { BaseAddress = baseUri };           

            //写个cookie
            Cookie cookie = new Cookie();
            cookie.Name = "cookie_0";
            cookie.Value = "0";
            cookie.Domain = "localhost";
            handler.CookieContainer.Add(cookie);

            string token = "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoid3l0IiwiaHR0cDovL3NjaGVtYXMubWljcm9zb2Z0LmNvbS93cy8yMDA4LzA2L2lkZW50aXR5L2NsYWltcy9yb2xlIjpbImFkbWluIiwicm9sZTEiXSwiVGVuYW50IjoiMmMzMGNlYjc1MzRmNDQ4NjliZDA0ODdlMTg3YmIzNGQiLCJuYmYiOjE2NDAwOTAwNTIsImV4cCI6MTY0MDE3NjQ1MiwiaXNzIjoiaHR0cDovL3h0amF0c3djOjUwMDAiLCJhdWQiOiJodHRwOi8vbG9jYWxob3N0OjM5Mjc0In0.c0PVLk5jfimphgdmd5SOHUtIoiWzQ8YUs7cMpbabmGs";

            //第一次请求
            var request = new HttpRequestMessage(HttpMethod.Get, "api/v1/Demo/User/WriteCookie/1");
            request.Headers.Add("Authorization", token);
            var response = await client.SendAsync(request);
            response.EnsureSuccessStatusCode();
            Console.WriteLine(await response.Content.ReadAsStringAsync());

            //第二次请求
            request = new HttpRequestMessage(HttpMethod.Get, "api/v1/Demo/User/WriteCookie/2");
            request.Headers.Add("Authorization", token);
            response = await client.SendAsync(request);
            response.EnsureSuccessStatusCode();
            Console.WriteLine(await response.Content.ReadAsStringAsync());

            List<Cookie> cookies = handler.CookieContainer.GetCookies(baseUri).Cast<Cookie>().ToList();

            return Ok(cookies);
        }

    }
}
